package br.com.robot;

import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class RobotExecutorB 
{
	private ExecutorService executor  = Executors.newFixedThreadPool( 30 );
	private Calendar        session   = null;
	private RobotStatus     status    = RobotStatus.PARADO;
	private StringBuffer    sbLogErro = new StringBuffer( );

	abstract public void start( ) throws Exception;
	
	public RobotExecutorB( )
	{
		setSession( Calendar.getInstance( ) );
	}
	
	public void run( )
	{
		executor.execute( new Runnable( )
		{
			@Override
			public void run( )
			{
				status = RobotStatus.RODANDO;
				
				try
				{
					start( );
				}
				catch( Exception e )
				{
					logaErro( e );
					e.printStackTrace( );
				}
				
				executor.shutdown( );
				
				verificadorDoRobo( );
			}
		} );
	}
	
	private void verificadorDoRobo( )
	{
		try
		{
			new Thread( new Runnable( )
			{
				@Override
				public void run( )
				{
					while( !executor.isTerminated( ) ) { }
					
					status = RobotStatus.PARADO;
				}
			} ).start( );
		}
		catch( Exception e )
		{
			logaErro( e );
			e.printStackTrace( );
			
			status = RobotStatus.PARADO;
		}
	}
	
	public void parar( )
	{
		status = RobotStatus.PARADO;
		executor.shutdownNow( );
	}

	public RobotStatus verificarStatus( )
	{
		return status;
	}

	public String infLog( )
	{
		return sbLogErro.toString( );
	}
	
	protected void logaErro( Exception e )
	{
		StackTraceElement[] stackTrace = e.getStackTrace( );
		
		sbLogErro.append( e.getMessage( ) + "<br />\r\n" );
		
		for( StackTraceElement stackTraceElement : stackTrace ) 
		{
			sbLogErro.append( stackTraceElement.getFileName( )   );
			sbLogErro.append( stackTraceElement.getMethodName( ) );
			sbLogErro.append( stackTraceElement.getLineNumber( ) );
			
			sbLogErro.append( "<br />\r\n" );
		}
	}
	
	protected void startNewThread( Runnable run )
	{
		executor.execute( run );
	}
	
	protected void logaMenssagem( String menssagem )
	{
		sbLogErro.append( menssagem + "<br />\r\n" );
	}

	public Calendar getSession( )
	{
		return session;
	}

	private void setSession( Calendar dataAtual ) 
	{
		this.session = dataAtual;
	}
}